import axios from 'axios'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'
import { Loading } from 'element-ui'
import store from '@/store'
let loading = null
let pending = {}
const CancelToken = axios.CancelToken
const removePending = (key, isRequest = false) => {
  if (pending[key] && isRequest) {
    pending[key]('取消重复请求')
  }
  delete pending[key]
}
const getRequestIdentify = (config) => {
  const url = config.url
  if (config.method === 'post') {
    return encodeURIComponent(config.url + JSON.stringify(config.data))
  }
  return encodeURIComponent(url + JSON.stringify(config.params))
}
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 请求地址
  timeout: 60000, // request timeout
  withCredentials: true
})

// request interceptor
service.interceptors.request.use(
  config => {
    // get请求取消强缓存
    if (config.method === 'get') {
      config.headers['Cache-Control'] = 'no-cache'
      config.headers['Pragma'] = 'no-cache'
    }
    const requestData = getRequestIdentify(config)
    removePending(requestData, true)
    config.cancelToken = new CancelToken(c => {
      pending[requestData] = c
    })
    // 全局loading
    if (config.isDefaultLoading) {
      loading = Loading.service()
    }
    // 只用于表格loading
    if (config.tabelLoading) {
      store.state.tabelLoading = true
    }

    if (getToken()) {
      config.headers['accessToken'] = getToken()
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    const { code } = res
    if (response.config.isDefaultLoading) {
      loading.close()
    }
    if (response.config.tabelLoading) {
      store.state.tabelLoading = false
    }

    if (code !== 10000) {
      if (code === 10915) {
        Message({
          message: '您的账号已在其它终端登录，请重新登录！',
          type: 'error'
        })
        setTimeout(() => {
          store.dispatch('user/logout')
        })
        return Promise.reject(res)
      }
      if (code === 10401 || code === 10403 || code === 10404) {
        Message({
          message: res.message || res.msg || 'token无效,请重新登录',
          type: 'error'
        })
        setTimeout(() => {
          store.dispatch('user/logout')
        })
        return Promise.reject(res)
      }
      if (!response.config.noToast) {
        Message({
          message: res.msg || res.error || '服务异常',
          type: 'error'
        })
      }

      return Promise.reject(res)
    } else {
      return res
    }
  },
  error => {
    // Message({
    //   message: '请检查网络',
    //   type: 'error'
    // })
    loading && loading.close()
    store.state.tabelLoading = false
    return Promise.reject(error)
  }
)
export default service
